package job.work.service.auth;

import job.work.domain.response.AuthCode;
import job.work.domain.system.entity.pojo.dto.AuthToken;
import job.work.domain.system.entity.pojo.model.SystemUser;
import job.work.framework.ExceptionCast;
import job.work.service.redis.VcodeManager;
import job.work.service.system.service.SystemService;
import job.work.utils.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author Administrator
 * @version 1.0
 **/
@Service
@Slf4j
public class AuthService {


    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RestTemplate restTemplate;
    @Autowired
    SystemService systemService;
    @Resource
    VcodeManager vcodeManager;

    public AuthToken mobileLogin(String mabile, String verifycode) {
        SystemUser systemMobile = this.validate(mabile, verifycode);
        if (systemMobile == null) {
            ExceptionCast.cast(AuthCode.AUTH_ACCOUNT_NOTEXISTS);
        }
        //TODO 把token 保存到Redis中

        return JwtTokenUtils.createTokenUser(systemMobile);

    }


    //验证规则
    private SystemUser validate(String mobileInRequest, String verifycode) {

        this.validateVie(mobileInRequest, verifycode);
        SystemUser systemMobile = systemService.findSystemMobile(mobileInRequest);

        return systemMobile;
    }

    public void validateVie(String mobileInRequest, String verifycode) {
        if (StringUtils.isEmpty(verifycode)) {
            // throw new SessionAuthenticationException("验证码不能为空");
            ExceptionCast.cast(AuthCode.AUTH_VERIFYCODE_ERROR);
        }

        if (StringUtils.isEmpty(mobileInRequest)) {
            ExceptionCast.cast(AuthCode.AUTH_VERIFYCODE_ERROR);
        }

        if (StringUtils.isEmpty(verifycode)) {
            ExceptionCast.cast(AuthCode.AUTH_VERIFYCODE_ERROR);
        }

        Object vcode = vcodeManager.getVcode(mobileInRequest);
        if (Objects.isNull(vcode)) {
            ExceptionCast.cast(AuthCode.AUTH_VERIFYCODE_ERROR);

        }

        if (!vcode.toString().equals(verifycode)) {
            ExceptionCast.cast(AuthCode.AUTH_VERIFYCODE_ERROR);
        }
    }


}
